#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int mod = 1e9 + 7;
    int dfs(vector<vector<int>>& grid, vector<vector<int>>& dp, vector<vector<bool>>& dpmap, int x, int y, int n, int m)
    {
        if (dpmap[x][y] == true) return dp[x][y];
        dpmap[x][y] = true;

        for (int k = 0; k < 4; k++) {
            int a = x + dx[k], b = y + dy[k];
            if (a < 0 || a >= n || b < 0 || b >= m || grid[a][b] <= grid[x][y]) continue;
            dp[x][y] = (dp[x][y] + dfs(grid, dp, dpmap, a, b, n, m)) % mod;
        }
        return dp[x][y];
    }
    int countPaths(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size(), ret = 0;
        vector<vector<int>> dp(n, vector<int>(m, 1));
        vector<vector<bool>> dpmap(n, vector<bool>(m, false));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                ret = (ret + dfs(grid, dp, dpmap, i, j, n, m)) % mod;
        return ret;
    }
};